<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/4/14
 * Time: 11:31
 */
namespace app\admin\controller;
use app\common\model\PermitModel;
use think\Controller;
use think\Db;


class Permit extends Intercept
{

    public function index()
    {
        try{
            $list = Db::name('cms_blog_permit')->order(['id' => 'desc'])->select();
            $this->assign('list', $list);
            return $this->fetch('index');
        }catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function add()
    {
        try{
            $list = Db::name('cms_blog_menu')->where('parent', 0)->select();
            $this->assign('list', $list);
            return $this->fetch();
        }catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function edit($id)
    {
        try{
            $res = Db::name('cms_blog_menu')->select();
            $list = [];
            foreach ($res as $arr) {
                $list[$arr['parent']][] = $arr;
            }

            $permitModel = new  PermitModel();
            $data = $permitModel->getPermitInfo(['id' => $id]);
            $data['modules'] = implode("\n", json_decode($data['modules'], true));
            $this->assign('data', $data);
            $this->assign('list', $list);
            return $this->fetch();
        }catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function updateData()
    {
        try{
            if(request()->isPost())
            {
                $param = input('param.');
                $updateData['type']  = 'admin';
                $updateData['parent']  = $param['parent'];
                $updateData['name']  = $param['name'];
                $updateData['modules']  = json_encode(array_map(function ($v) {
                    return trim($v);
                }, explode("\n", strtolower($param['modules']))));
                $permitModel = new PermitModel();
                if (isset($param['id'])) {
                    $id = $param['id'];
                    $updateData['update_time'] = time();
                    $permitModel->update($updateData, ['id' => $id]);
                    return ['status' => 1, 'message' => '修改成功'];
                } else {
                    $updateData['create_time'] = time();
                    $permitModel->insert($updateData);
                    return ['status' => 1, 'message' => '添加成功'];
                }
            }
            return $this->fetch();
        }catch (\Exception $e) {
            echo $e->getMessage();
        }
    }


}